<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <div class="tips">
            <span>总记录数: {{ total }} 条</span>
          </div>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="exportEmpFn">excel导出</el-button>
          <el-button type="primary" size="small" @click="addEmpFn">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'timeOfEntry', order: 'descending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />

          <el-table-column label="头像" width="110">
            <template #default="{row}">
              <!-- <img :src="scope.row.staffPhoto" alt="" width="80"> -->
              <el-image style="width: 100px; height: 100px" :src="row.staffPhoto" class="avatar" @click="createQr(scope.row)">
                <!-- 具名插槽新语法  图片加载出错的时候自动显示 -->
                <template #error>
                  <!-- <i class="el-icon-picture-outline" /> -->
                  <img src="@/assets/common/bigUserHeader.png" width="80">
                </template>
              </el-image>
            </template>
          </el-table-column>

          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ formOfEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable>
            <template #default="{row}" prop="timeOfEntry">
              {{ formatDate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="goDetailFn(row.id)">查看</el-button>
              <el-button type="text" size="small" @click="editRoleFn(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmpFn(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            :page-size="params.size"
            @current-change="currentPageFn"
          />
        </div>
      </el-card>
    </div>
    <!-- 新增弹框 -->
    <add-employee
      :show-view-dialog="showDialog"
      @close-dialog="closeDialogFn"
      @update-list="getEmployeeList"
    />
    <!-- 分配权限弹框 -->
    <assign-role :show-role="showRoleDialog" :cur-id="curId" @close-role="closeRoleFn" />
  </div>
</template>
<script>
import { getEmployeeListAPI, delEmployeeAPI } from '@/api/employees'
import AddEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'
import dayjs from 'dayjs'
import { getExportData } from '@/utils/excelData'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      list: [], // 员工列表
      params: {
        page: 1,
        size: 5
      },
      total: 0, // 总记录
      showDialog: false, // 控制新增弹框
      showRoleDialog: false, // 控制分配角色弹框
      curId: null
    }
  },
  mounted() {
    this.getEmployeeList()
  },
  methods: {
    // 获取员工列表
    async  getEmployeeList() {
      const res = await getEmployeeListAPI(this.params)
      const { rows, total } = res.data
      this.list = rows
      this.total = total
    },
    // 聘用形式的转化
    formOfEmployment(type) {
      const map = {
        1: '正式',
        2: '非正式'
      }
      return map[type]
    },
    // 分页功能
    currentPageFn(value) {
      // console.log(value)
      this.params.page = value
      this.getEmployeeList()
    },
    // 删除功能
    delEmpFn(id) {
      // 删除部门
      // element封装的函数
      this.$confirm('你确认要删除此部门吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 删除操作成功
        await delEmployeeAPI(id)
        // 优化 当只有最后一页，就是回到前一页
        this.list.length <= 1 && this.params.page >= 1 && this.params.page--
        // 添加提示
        this.$message.success('删除操作成功')
        // 更新数据
        this.getEmployeeList()
      }).catch(error => {
        console.log(error)
      })
    },
    // 新增功能
    addEmpFn() {
      this.showDialog = true
    },
    // 关闭弹框-子传父
    closeDialogFn() {
      this.showDialog = false
    },
    // 格式化时间
    formatDate(value, str = 'YYYY-MM-DD') {
      return dayjs(value).format(str)
    },
    // 导出
    exportEmpFn() {
      import('@/vendor/Export2Excel').then(async excel => {
        console.log('excel', excel)// .then 知道是一个promise对象
        // excel 有2种方法
        // export_json_to_excel
        // export_table_to_excel
        // 1.准备表头中的中英文对应关系
        const headerRelation = {
          '手机号': 'mobile',
          '姓名': 'username',
          '入职日期': 'timeOfEntry',
          '工号': 'workNumber',
          '转正日期': 'correctionTime',
          '部门': 'departmentName'
        }
        // 2.调用接口准备表格数据 (从数组库拉取当前页的最新的数据完成导出)
        const res = await getEmployeeListAPI(this.params)
        // 3.调用处理方法进行数据处理
        const { data, header } = getExportData(res.data.rows, headerRelation)
        // 对于到插件需要的位置
        excel.export_json_to_excel({
          header: header, // 表头数据，有几项
          data: data, // 具体数据 必填 // 表格数据 (二维数组)有几列
          filename: '员工列表',
          autoWidth: true,
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 查看详情
    goDetailFn(id) {
      this.$router.push({
        path: '/employees/detail',
        query: {
          id
        }
      })
    },
    // 分配权限
    editRoleFn(id) {
      this.showRoleDialog = true
      this.curId = id
    },
    closeRoleFn() {
      this.showRoleDialog = false
    }
  }
}

</script>
<style lang="scss" scoped>
 .tips {
    line-height: 34px;
    padding: 0px 15px;
    border-radius: 5px;
    border: 1px solid rgba(145, 213, 255, 1);
    background: rgba(230, 247, 255, 1);
    i {
      margin-right: 10px;
      color: #409eff;
    }
  }
</style>
